﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Threading;
using System.Data.SqlClient;
using System.Collections;
using LHS.Core.TableInfo;
using MS.Core.Base.Transaction;

namespace LHS.Win
{
    public partial class frmBackupSchedule : Form
    {
        LHS.Core.Authority.AuthorityController objController = new LHS.Core.Authority.AuthorityController();
       // Methods
        public frmBackupSchedule()
        {
            this.InitializeComponent();
        }
        private void cmdCancel_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void cmdOk_Click(object sender, EventArgs e)
        {
            if (this.rdBackupAuto.Checked)
            {
                int num = 0;
                string s = "";
                string str2 = "";
                int num2 = 0;
                int num3 = 0;
                int num4 = 0;
                int num5 = 0;
                if ((this.dtpBeginAtTime.Value >= this.dtpEndAtTime.Value) && this.rbOccursEvery.Checked)
                {
                    MessageBox.Show("Thời gian bắt đầu phải nhỏ hơn thời gian kết thúc", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else
                {
                    if (this.rbOccursEvery.Checked)
                    {
                        if (this.cboTimeUnit.SelectedItem.ToString() == "Minute(s)")
                        {
                            num = 4;
                        }
                        else if (this.cboTimeUnit.SelectedItem.ToString() == "Hour(s)")
                        {
                            num = 8;
                        }
                        s = this.dtpBeginAtTime.Value.ToLongTimeString();
                        str2 = this.dtpEndAtTime.Value.ToLongTimeString();
                    }
                    else if (this.rbOccursAt.Checked)
                    {
                        num = 1;
                        s = this.dtpOccursAtTime.Value.ToLongTimeString();
                        str2 = "235959";
                    }
                    if (s.Substring(s.Length - 2) == "PM")
                    {
                        num5 = int.Parse(s.Substring(0, s.IndexOf(':'))) + 12;
                        s = num5.ToString() + s.Substring(s.IndexOf(':'));
                    }
                    s = s.Substring(0, s.Length - 2).Replace(":", "");
                    if (str2.Substring(str2.Length - 2) == "PM")
                    {
                        str2 = ((int.Parse(str2.Substring(0, str2.IndexOf(':'))) + 12)).ToString() + str2.Substring(str2.IndexOf(':'));
                    }
                    str2 = str2.Substring(0, str2.Length - 2).Replace(":", "");
                    if (this.rbDaily.Checked)
                    {
                        num2 = 4;
                        num3 = int.Parse(this.cboDaily.Value.ToString());
                        num4 = 0;
                    }
                    else if (this.rbWeekly.Checked)
                    {
                        num2 = 8;
                        num4 = int.Parse(this.cboWeekly.Value.ToString());
                        if (this.chkSun.Checked)
                        {
                            num3++;
                        }
                        if (this.chkMon.Checked)
                        {
                            num3 += 2;
                        }
                        if (this.chkTue.Checked)
                        {
                            num3 += 4;
                        }
                        if (this.chkWen.Checked)
                        {
                            num3 += 8;
                        }
                        if (this.chkThur.Checked)
                        {
                            num3 += 0x10;
                        }
                        if (this.chkFri.Checked)
                        {
                            num3 += 0x20;
                        }
                        if (this.chkSat.Checked)
                        {
                            num3 += 0x40;
                        }
                    }
                    else if (this.rbMonthly.Checked)
                    {
                        num3 = int.Parse(this.cboEveryDayOfMonth.Value.ToString());
                        num4 = int.Parse(this.cboMonthly.Value.ToString());
                        num2 = 0x10;
                    }
                    TransactionManager trans = TransactionManager.ThreadTransactionMgr();
                    try
                    {
                        trans.BeginTransaction();
                        Hashtable hashBackup = new Hashtable();
                        hashBackup[InfoBackup.FREQTYPE] = num2;
                        hashBackup[InfoBackup.FREQINTERVAL] = num3;
                        hashBackup[InfoBackup.FREQSUBDAYTYPE] = num;
                        hashBackup[InfoBackup.FREQSUBDAYINTERVAL] = this.cboDailyFrequencyTime.Value;
                        hashBackup[InfoBackup.ACTIVESTARTTIME] = int.Parse(s);
                        hashBackup[InfoBackup.ACTIVEENDTIME] = int.Parse(str2);
                        hashBackup[InfoBackup.FREQRECURRENCEFACTOR] = num4;
                        hashBackup[InfoBackup.FILEPATH] = this.txtFilePath.Text;

                        objController.BackUpDatabaseAuto(hashBackup);
                        trans.CommitTransaction();
                        MessageBox.Show("Backup schedule successful", "Backup schedule", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        
                    }
                    catch(Exception ex)
                    {
                        trans.RollbackTransaction();
                        MessageBox.Show("Backup bị lỗi. Xin vui lòng kiểm tra lại tên đường dẫn \n " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                }
            }
            else if (this.rdBackupManual.Checked)
            {
                if (this.txtFilePath.Text == "")
                {
                    MessageBox.Show("xin vui lòng chọn file backup", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else
                {
                    string text = "";
                    text = this.txtFilePath.Text;
                    base.ParentForm.Cursor = Cursors.AppStarting;
                    this.th1 = new Thread(new ThreadStart(this.Thread1));
                    this.th1.Start();
                    this.Cursor = Cursors.WaitCursor;
                    TransactionManager trans = TransactionManager.ThreadTransactionMgr();
                    try
                    {
                        trans.BeginTransaction();
                        Hashtable hashBackup = new Hashtable();
                        hashBackup[InfoBackup.FILENAME] = text.Substring(text.LastIndexOf(@"\") + 1);
                        hashBackup[InfoBackup.FILEPATH] = text.Substring(0, text.LastIndexOf(@"\") + 1);

                        objController.BackUpDatabaseManual(hashBackup);
                        trans.CommitTransaction();
                    }
                    catch(Exception ex)
                    {
                        trans.RollbackTransaction();
                        MessageBox.Show("Backup bị lỗi. Xin vui lòng kiểm tra lại tên đường dẫn \n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    this.sp.EndDisplay();
                    this.th1 = null;
                    this.Cursor = Cursors.Arrow;
                    base.ParentForm.Cursor = Cursors.Arrow;
                    MessageBox.Show("Backup successful", "Backup", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
        }

        private void cmdOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.FilterIndex = 1;
            dialog.RestoreDirectory = true;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                this.txtFilePath.Text = dialog.FileName;
            }
        }

        private void frmBackupSchedule_Load(object sender, EventArgs e)
        {
            this.gbDaily.Visible = false;
            this.gbMonthly.Visible = false;
            this.gbWeekly.Visible = false;
            DataTable dtBackup = objController.GetBackUpDT();
            if (dtBackup.Rows.Count == 0)
            {
                this.rdBackupManual.Checked = true;
            }
            else
            {
                DataRow drBackup = dtBackup.Rows[0];
                this.rdBackupAuto.Checked = true;
                string s = "";
                string str2 = "";
                s = drBackup[InfoBackup.ACTIVESTARTTIME].ToString();
                str2 = drBackup[InfoBackup.ACTIVEENDTIME].ToString();
                string str3 = DateTime.Now.ToShortDateString();
                if (s.Length.ToString() == "5")
                {
                    s = s.Insert(2, ":").Insert(4, ":");
                }
                else if (s.Length.ToString() == "6")
                {
                    s = s.Insert(2, ":").Insert(5, ":");
                }
                if (str2.Length.ToString() == "5")
                {
                    str2 = str2.Insert(2, ":").Insert(4, ":");
                }
                else if (str2.Length.ToString() == "6")
                {
                    str2 = str2.Insert(2, ":").Insert(5, ":");
                }
                s = str3 + " " + s;
                str2 = str3 + " " + str2;
                if (drBackup[InfoBackup.FREQTYPE].ToString() == "4")
                {
                    this.rbDaily.Checked = true;
                    this.cboDaily.Value = decimal.Parse(drBackup[InfoBackup.FREQINTERVAL].ToString());
                }
                else if (drBackup[InfoBackup.FREQTYPE].ToString() == "8")
                {
                    this.cboWeekly.Value = decimal.Parse(drBackup[InfoBackup.FREQRECURRENCEFACTOR].ToString());
                    int num = int.Parse(drBackup[InfoBackup.FREQINTERVAL].ToString());
                    this.rbWeekly.Checked = true;
                    if ((num % 2) != 0)
                    {
                        this.chkSun.Checked = true;
                        num--;
                    }
                    if (num >= 0x40)
                    {
                        this.chkSat.Checked = true;
                        num -= 0x40;
                    }
                    if (num >= 0x20)
                    {
                        this.chkFri.Checked = true;
                        num -= 0x20;
                    }
                    if (num >= 0x10)
                    {
                        this.chkThur.Checked = true;
                        num -= 0x10;
                    }
                    if (num >= 8)
                    {
                        this.chkWen.Checked = true;
                        num -= 8;
                    }
                    if (num >= 4)
                    {
                        this.chkTue.Checked = true;
                        num -= 4;
                    }
                    if (num >= 2)
                    {
                        this.chkMon.Checked = true;
                        num -= 2;
                    }
                }
                else if (drBackup[InfoBackup.FREQTYPE].ToString() == "16")
                {
                    this.rbMonthly.Checked = true;
                    this.cboEveryDayOfMonth.Value = decimal.Parse(drBackup[InfoBackup.FREQINTERVAL].ToString());
                    this.cboMonthly.Value = decimal.Parse(drBackup[InfoBackup.FREQRECURRENCEFACTOR].ToString());
                }
                if (drBackup[InfoBackup.FREQSUBDAYTYPE].ToString() == "1")
                {
                    this.rbOccursAt.Checked = true;
                    this.dtpOccursAtTime.Value = DateTime.Parse(s);
                }
                else
                {
                    this.rbOccursEvery.Checked = true;
                    this.dtpBeginAtTime.Value = DateTime.Parse(s);
                    this.dtpEndAtTime.Value = DateTime.Parse(str2);
                    if (drBackup[InfoBackup.FREQSUBDAYTYPE].ToString() == "4")
                    {
                        this.cboTimeUnit.SelectedItem = "Minute(s)";
                    }
                    else
                    {
                        this.cboTimeUnit.SelectedItem = "Hour(s)";
                    }
                    this.cboDailyFrequencyTime.Value = decimal.Parse(drBackup[InfoBackup.FREQSUBDAYINTERVAL].ToString());
                }
            }
        }

        #region Radio CheckChanged
        
        private void rbBackup_CheckedChanged(object sender, EventArgs e)
        {
            this.gbBackup.Enabled = true;
        }

        private void rbDaily_CheckedChanged(object sender, EventArgs e)
        {
            this.gbDaily.Visible = true;
            this.gbMonthly.Visible = false;
            this.gbWeekly.Visible = false;
        }

        private void rbMonthly_CheckedChanged(object sender, EventArgs e)
        {
            this.gbMonthly.Visible = true;
            this.gbDaily.Visible = false;
            this.gbWeekly.Visible = false;
        }

        private void rbOccursAt_CheckedChanged(object sender, EventArgs e)
        {
            this.cboDailyFrequencyTime.Enabled = false;
            this.cboTimeUnit.Enabled = false;
            this.dtpBeginAtTime.Enabled = false;
            this.dtpEndAtTime.Enabled = false;
            this.dtpOccursAtTime.Enabled = true;
        }

        private void rbOccursEvery_CheckedChanged(object sender, EventArgs e)
        {
            this.dtpOccursAtTime.Enabled = false;
            this.cboDailyFrequencyTime.Enabled = true;
            this.cboTimeUnit.Enabled = true;
            this.dtpBeginAtTime.Enabled = true;
            this.dtpEndAtTime.Enabled = true;
            this.cboTimeUnit.SelectedIndex = 1;
        }

        private void rbWeekly_CheckedChanged(object sender, EventArgs e)
        {
            this.gbWeekly.Visible = true;
            this.gbDaily.Visible = false;
            this.gbMonthly.Visible = false;
        }

        private void rdBackupAuto_CheckedChanged(object sender, EventArgs e)
        {
            this.gbOccurs.Enabled = true;
            this.gbDailyFrequency.Enabled = true;
            this.gbDaily.Enabled = true;
            this.gbWeekly.Enabled = true;
            this.gbMonthly.Enabled = true;
            this.txtFilePath.Enabled = false;
        }

        private void rdBackupManual_CheckedChanged(object sender, EventArgs e)
        {
            this.gbOccurs.Enabled = false;
            this.gbDailyFrequency.Enabled = false;
            this.gbDaily.Enabled = false;
            this.gbWeekly.Enabled = false;
            this.gbMonthly.Enabled = false;
            this.txtFilePath.Enabled = true;
        }

        private void rdRestore_CheckedChanged(object sender, EventArgs e)
        {
            this.gbBackup.Enabled = false;
            this.rdBackupAuto.Checked = false;
            this.rdBackupManual.Checked = false;
        }

        #endregion

        private void Thread1()
        {
            this.sp = new SplashScreen();
            this.sp.Show();
            this.sp.BeginDisplay();
        }
    }
}